# !/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :teachers.py
# @Time      :2022/7/22 14:13
# @Author    :吕华龙
import redis
from flask import Blueprint, jsonify
from flask_restful import Api, Resource, reqparse

from models.model import db, Stu, Teacher

teacher_bp = Blueprint("teacher", __name__, url_prefix="/teacher")

api = Api(teacher_bp)


# 教师视图
class Teac(Resource):
    # 教师列表
    def get(self):
        user_all = Teacher.query.all()
        list1 = []
        for i in user_all:
            dict1 = {
                "id": i.id,
                "name": i.name,
                "attention_num": i.attention_num,
                "phone": i.phone,
                "password": i.password,
                "info": i.info,
                "create_time": i.create_time,
                "sttus": i.status,
                "photo": i.photo,
            }
            list1.append(dict1)
        return jsonify({
            "code": 200,
            "msg": "返回成功",
            "data": list1
        })

    # 查询单条数据教师
    def post(self):
        req = reqparse.RequestParser()
        req.add_argument('id')
        args = req.parse_args()
        # print(args)
        req.add_argument("id")
        print(type(args['id']))
        # args = req.parse_args()
        # print("---------------------",args["id"])
        teac_info = Teacher.query.filter(Teacher.id == args['id']).first()

        dict1 = {
            "id": teac_info.id,
            "name": teac_info.name,
            "attention_num": teac_info.attention_num,
            "phone": teac_info.phone,
            "password": teac_info.password,
            "info": teac_info.info,
            "create_time": teac_info.create_time,
            "sttus": teac_info.status,
            "photo": teac_info.photo,
        }
        return jsonify({
            "code": 200,
            "msg": "查询单条老师数据成功",
            "data": dict1
        })


from utils.jwt_tool import JWT_tool


# 老师登录注册
class TeacherView(Resource):
    def post(self):
        # 获取前端数据
        resp = reqparse.RequestParser()
        resp.add_argument("name")
        resp.add_argument("phone")
        resp.add_argument("password")
        resp.add_argument("sms_code", type=str)
        args = resp.parse_args()
        print("-----", args['name'], type(args['name']))
        print("-------", args['phone'], type(args['phone']))
        print("-----------", args['password'], type(args['password']))
        print("-----------------", args['sms_code'], type(args['sms_code']))
        j = JWT_tool()
        # 连接redis
        redis_cli = redis.Redis(host="127.0.0.1", port=6379, db=4, password="123")
        # 判断手机号和用户名是否存在
        teachers = Teacher.query.filter(Teacher.phone == args['phone']).first()
        print("-------------", teachers)
        # 如果没有就注册
        if not teachers:
            # 判断验证码是否正确
            redis_phone = redis_cli.get(args['phone'])
            print(">>>>>>>>>>>>>>>", redis_phone.decode(), type(redis_phone.decode()))
            if redis_phone.decode() == args['sms_code']:
                teacher = Teacher(name=args['name'], phone=args['phone'], password=args['password'])
                db.session.add(teacher)
                db.session.commit()
                token = j.create_token({
                    "id": teacher.id,
                    "name": teacher.name,
                    "phone": teacher.phone
                }, 3600)
                return jsonify({'code': 200, 'msg': '注册老师成功', 'token': token})
        # 如果存在就判断用户输入的数据是否跟数据库一致
        if teachers.name == args['name'] and teachers.phone == args['phone'] and teachers.password == args['password']:
            token = j.create_token({
                "id": teachers.id,
                "name": teachers.name,
                "phone": teachers.phone
            }, 3600)
            return jsonify({'code': 200, 'msg': '登录成功', 'token': token})
        # 否则就是用户信息不一样
        else:
            return jsonify({'code': 400, 'msg': '用户信息错误，登录失败'})


# 创建路由
api.add_resource(Teac, "/teacher_all")
# 注册登录老师
api.add_resource(TeacherView, "/teacher_login")
